package net.ocps.tchs.soap.event;

import net.ocps.tchs.soap.Main;
import net.ocps.tchs.soap.entity.Entity;
import net.ocps.tchs.soap.entity.Player;

public class EventScheduler implements Runnable {

	public EventScheduler() {
		new Thread( this ).start();
		System.out.println( "EVENTS SYSTEM INITIALIZED" );
	}

	@Override
	public void run() {
		Entity e;
		//int flushed = 0;
		//int leftInList = 0;
		while(true) {
			try {
				/* DO EVENTS HERE!!! OR DONT */
				for( int i = 0; i < Main.entitys.size(); i ++ ) {
					e = Main.entitys.get( i );

					if( !(e instanceof Player) ) {
						e.queueEvent( e.mainEvent );
						e.sendEvent( e.events.get( 0 ) );
						e.events.remove( 0 );
						//flushed ++;
					}
					if( !e.equals( null ) && !e.events.isEmpty() ) {
						try {
							e.sendEvent( e.events.get( 0 ) );
							e.events.remove( 0 );
							//flushed ++;
						} catch( Exception ee ) {
							System.err.println("Error processing event["+e.events.get( 0 ).getClass().getSimpleName()+"] because of: "+ee.getCause()+", unclogging..." );
						}
					}
					//leftInList += e.events.size();
				}

				/*if( false && flushed != 0 )
					System.out.println("[DEBUG] flushed "+flushed+" event(s). "+leftInList+" event(s) queued");
				flushed = 0;
				leftInList = 0;*/
				Thread.sleep( Main.EVENT_FLUSH_MILLIS ); //CHANGE THIS VARIABLE TO YOUR CONTENT WITH IT
			} catch ( Exception ex ) {
				ex.printStackTrace();
			}
		}
	}

}
